package com.school.movie.common.interceptor;

import com.school.movie.common.constant.Constants;
import com.school.movie.common.utils.ShiroUtil;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;
import java.util.Objects;

/**
 * ws鉴权拦截器，非登陆用户无法进行握手
 *
 * @author swift
 */
@Component
public class WebSocketHanShakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (Objects.isNull(ShiroUtil.getCurrentUser())) {
            return false;
        }
        attributes.put(Constants.User.WebSocket.USER_ID, ShiroUtil.getCurrentUser().getMobile());
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

}
